package com.gears_software.sxdc.dccx.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.adapter.TripInformationAdapter;
import com.gears_software.sxdc.dccx.data.finder.ICPOrderFinder;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.CPOrderDetailModel;
import com.gears_software.sxdc.dccx.data.model.CPOrderListDetailModel;
import com.gears_software.sxdc.dccx.data.model.CPOrderModel;
import com.gears_software.sxdc.dccx.data.model.CheckCancelModel;
import com.gears_software.sxdc.dccx.data.model.request.RCheckDriverCancelModel;
import com.gears_software.sxdc.dccx.data.model.request.RDriverCancelModel;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.ui.event.UpdateTripListEvent;
import com.gears_software.sxdc.dccx.ui.util.MaterialDialogProgress;
import com.gears_software.sxdc.dccx.ui.util.OttoBus;
import com.github.mzule.activityrouter.annotation.Router;
import com.orhanobut.logger.Logger;
import com.sdsmdg.tastytoast.TastyToast;
import com.squareup.otto.Subscribe;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.rest.spring.annotations.RestService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import qiu.niorgai.StatusBarCompat;

/**
 * Created by SunMuran on 2017/7/29.
 */
@EActivity(R.layout.trip_information)
@Router(value = "tripinfo/:id", isEActivity = true)
public class TripInformationActivity extends Activity {

    @App
    DCCXApplication app;
    @ViewById
    TextView actionbar_title;
    @ViewById
    TextView back_icon;
    @ViewById
    TextView right_icon;
    @ViewById
    TextView tv_jiantou_icon;
    @ViewById
    ListView lv_listView;
    @ViewById
    TextView txt_carmodel;
    @ViewById
    TextView txt_departtime;
    @ViewById
    TextView txt_start;
    @ViewById
    TextView txt_end;
    @ViewById
    TextView tv_price;
    @ViewById
    TextView txt_nodata_icon;
    @ViewById
    TextView txt_shengyu_seat;
    @ViewById
    TextView txt_cenceltrip;
    @ViewById
    RelativeLayout re_wu;
    @RestService
    ICPOrderFinder icpOrderFinder;
    @Bean
    GearsErrorHandler errorHandler;
    @Bean
    OttoBus bus;
    public String id;
    private TripInformationAdapter tripInformationAdapter;
    private CPOrderListDetailModel listDetailModel;
    private List<CPOrderDetailModel> detailModels = new ArrayList<CPOrderDetailModel>();
    MaterialDialogProgress progress;
    public int selectedItem = -1;
    int passengerNum;
    CPOrderModel orderModel = new CPOrderModel();


    @AfterViews
    void created() {
        actionbar_title.setText("行程信息");
        initIconfont();
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));

        id = getIntent().getStringExtra("id");
        icpOrderFinder.setRestErrorHandler(errorHandler);
        bus.register(this);
        progress = new MaterialDialogProgress(this);
        progress.show("正在加载...");
        getDetail();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            id = getIntent().getStringExtra("id");
            progress.show("正在加载...");
            getDetail();
        }
        Logger.d("aaaaa");

    }

    @Background
    void getDetail() {
        ResultModel<CPOrderListDetailModel> res = icpOrderFinder.getDriverOrderDetail(id);
        showResult(res);
    }

    @UiThread
    void showResult(ResultModel<CPOrderListDetailModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    listDetailModel = res.getData();
                    orderModel = listDetailModel.getOrder();
                    txt_carmodel.setText(orderModel.getCarmodel());
                    txt_start.setText(orderModel.getStartpoint());
                    txt_end.setText(orderModel.getEndpoint());
                    tv_price.setText(String.valueOf(orderModel.getPrice()));
                    passengerNum = orderModel.getPassengernum();
                    txt_shengyu_seat.setText("剩余" + passengerNum + "座");
                    if (passengerNum == 0) {
                        txt_shengyu_seat.setText("已预定满");
                    }

                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    txt_departtime.setText(sf.format(orderModel.getDeparttime()));
                    if (listDetailModel.getDetail() != null) {
                        detailModels = listDetailModel.getDetail();
                        if (detailModels.size() == 0) {
                            lv_listView.setVisibility(View.GONE);
                            re_wu.setVisibility(View.VISIBLE);
                            String departtime = sf.format(orderModel.getDeparttime());
                            String currenttime = sf.format(new Date());
                            if (departtime.compareTo(currenttime) < 0) {
                                txt_cenceltrip.setVisibility(View.GONE);
                            } else {
                                txt_cenceltrip.setVisibility(View.VISIBLE);
                            }
                            if (orderModel.getOrderstatus() == -1){
                                txt_cenceltrip.setEnabled(false);
                                txt_cenceltrip.setText("已取消");
                                txt_cenceltrip.setTextColor(ContextCompat.getColor(this,R.color.colorFontBigGray));
                            }

                        } else {
                            boolean isCancel = true;//已取消
                            if (detailModels.size() > 0) {
                                for (int i = 0; i < detailModels.size(); i++) {
                                    if (detailModels.get(i).getCancelparty() != null && !detailModels.get(i).getCancelparty().equals("")) {
                                    }else {
                                        isCancel = false;
                                        break;
                                    }
                                }
                            } else {
                                if (orderModel.getCanceltime() != null) {
                                    isCancel = true;
//                                    txt_cenceltrip.setEnabled(false);
//                                    txt_cenceltrip.setTextColor(ContextCompat.getColor(this, R.color.colorFontBigGray));
                                } else {
                                    isCancel = false;
                                }
                            }

                            if (isCancel) {
                                txt_cenceltrip.setVisibility(View.GONE);
                            } else {
                                txt_cenceltrip.setText("申请取消");
                            }


                            tripInformationAdapter = new TripInformationAdapter(this, detailModels);
                            lv_listView.setAdapter(tripInformationAdapter);
                            lv_listView.setVisibility(View.VISIBLE);
                            re_wu.setVisibility(View.GONE);

                        }
                    }
                }
            }
        }
        progress.dismiss();
    }

    void initIconfont() {
        back_icon.setTypeface(app.iconfont);
        txt_nodata_icon.setTypeface(app.iconfont);
        back_icon.setText(R.string.back_icon);
        right_icon.setVisibility(View.GONE);
        tv_jiantou_icon.setTypeface(app.iconfont);
    }

    @Subscribe
    public void onUpdateTrip(UpdateTripListEvent event) {
        int seat = event.getSeat();
        txt_shengyu_seat.setText("剩余" + String.valueOf(passengerNum - seat) + "座");
        if (passengerNum - seat == 0) {
            txt_shengyu_seat.setText("已预定满");
        }
        getDetail();
    }


    @Click
    void txt_cenceltrip() {
        Date departtime = orderModel.getDeparttime();
        Date currentdate = new Date();
        boolean isPay = true;
        if (detailModels.size() > 0){
            for (int i = 0; i < detailModels.size(); i++) {
                if (detailModels.get(i).getIspay() != null && detailModels.get(i).getIspay().equals("1")) {
                } else {
                    isPay = false;
                    break;
                }
            }
        }else{
            isPay =false;
        }

        if (currentdate.getTime() >= departtime.getTime()) {
            TastyToast.makeText(this, "已到出发时间不得取消行程", app.SHORT, app.WARNING);
        }else if (isPay) {
            TastyToast.makeText(this, "已有乘客支付订单，不得取消行程", app.SHORT, app.WARNING);
        } else {
            RCheckDriverCancelModel driverCancelModel = new RCheckDriverCancelModel();
            driverCancelModel.setOrderid(orderModel.getId());
            checkDriverCancel(driverCancelModel);
        }

    }

    @Background
    void checkDriverCancel(RCheckDriverCancelModel driverCancelModel){
        ResultModel<CheckCancelModel> res = icpOrderFinder.checkDriverCancel(driverCancelModel);
        showCheckDriverCancel(res);
    }

    @UiThread
    void showCheckDriverCancel(ResultModel<CheckCancelModel> res){
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    CheckCancelModel checkCancelModel = res.getData();
                    if (checkCancelModel.getIsok() == 1) {
                        driverCancel();
                    } else if (checkCancelModel.getIsok() == 2) {
                        new MaterialDialog.Builder(this)
                                .title("提示")
                                .titleGravity(GravityEnum.CENTER)
                                .titleColorRes(R.color.colorFontGray)
                                .content(checkCancelModel.getMsg())
                                .contentColorRes(R.color.colorFontGray)
                                .positiveText("确定")
                                .positiveColor(ContextCompat.getColor(this, R.color.colorFontBlue))
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        driverCancel();

                                    }
                                })
                                .negativeText("取消")
                                .negativeColor(ContextCompat.getColor(this, R.color.colorFontGray))
                                .onNegative(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                    }
                                })
                                .buttonsGravity(GravityEnum.CENTER)
                                .show();
                    }
                }
            } else {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
            }
        }
    }

    private void driverCancel(){
        new MaterialDialog.Builder(this)
                .title("取消原因")
                .inputRangeRes(2, 30, R.color.colorLine)
                .input(null, null, new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(MaterialDialog dialog, CharSequence input) {
                        // Do something
                        RDriverCancelModel cancelModel = new RDriverCancelModel();
                        cancelModel.setId(id);
                        cancelModel.setReason(input.toString());
                        goDriverCancel(cancelModel);
                    }
                }).negativeText("取消")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    @Background
    void goDriverCancel(RDriverCancelModel cancelModel) {
        ResultModel<String> res = icpOrderFinder.goDriverCancel(cancelModel);
        showCancelResult(res);
    }

    @UiThread
    void showCancelResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                txt_cenceltrip.setEnabled(false);
                txt_cenceltrip.setTextColor(ContextCompat.getColor(this, R.color.colorFontBigGray));
                if (detailModels == null || detailModels.size() == 0) {
                    txt_cenceltrip.setText("已取消");
                } else {
                    txt_cenceltrip.setText("取消中");
                }
                TastyToast.makeText(this, "取消申请提交成功", app.SHORT, app.SUCCESS);
            } else {
                String reg = "[\\u4e00-\\u9fa5]+";//判断是否全是中文
                if (res.getErrmsg().matches(reg)) {
                    TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
                } else {
                    TastyToast.makeText(this, "取消申请提交失败", app.SHORT, app.ERROR);
                }
            }
        }
    }


    @Click
    void back_icon() {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            getDetail();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bus.unregister(this);
    }
}
